﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using com.dz.ht.common;



namespace com.dz.ht.components.book.site_4
{
    public class CollectBookManager : IBookObject
    {
        Encoding m_site_encoding = Encoding.GetEncoding("gbk");
        const string c_reg_book = "<td[^<>]*?class=[\'\"]*odd[\'\"]*.*?>.*?<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>(.*?)</a>.*?</td>";
        const int c_book_link_index = 1;
        const int c_book_name_index = 2;

        const string c_reg_book_intro="<div[^<>]*id=[\'\"]*content[\'\"]*>.*?<h1>《(.*?)》</h1>.*?<a.*?>(.*?)</a>.*?<td.*?>.*?<a.*?>(.*?)</a>.*?\\|.*?<font.*?>(.*?)</font>.*?\\|.*?(\\d+).*?\\|.*?点击.*?(\\d+).*?收藏.*?(\\d+).*?<img[^<>]*srcs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>.*?<font[^<>]*class=[\'\"]*poptext[\'\"].*?>.*?</font>.*?<h2>.*?<font[^<>]*class=[\'\"]*poptext[\'\"].*?>.*?</font>(.*?)</td>";

        const int c_book_intro_name_index = 1;
        const int c_book_intro_author_index = 2;
        const int c_book_intro_subcategoryname_index = 3;
        const int c_book_intro_bookstatus_index = 4;
        const int c_book_intro_book_work_count_index = 5;
        const int c_book_intro_book_click_index = 6;
        const int c_book_intro_collect_index = 7;
        const int c_book_intro_icon_index = 8;
        const int c_book_intro_descrition_index = 9;

        //匹配分卷正则
        const string c_volume_reg = "<tr>.*?<td[^<>]*class=[\'\"]*vcss[\'\"]*[^<>]*>(.*?)</td>.*?</tr>";
        const string c_chapter_reg = "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*3z\\d+\\-\\d+\\.html)[\'\"]*[^<>]*?>(.*?)</a>";


        /// <summary>
        /// 获取首页所有的书籍
        /// </summary>
        /// <param name="i_book_default_url"></param>
        /// <returns></returns>
       public  Dictionary<string, string> CollectDefaultBookList(string i_book_default_url)
        {
            Dictionary<string, string> t_dic = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_default_url, m_site_encoding);
                if (!string.IsNullOrEmpty(t_html))
                {
             
                    MatchCollection t_ma = Regex.Matches(t_html, "<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*3zinfo\\-\\d+\\.html)[\'\"]*[^<>]*?>(.*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma != null && t_ma.Count > 0)
                    {
                        t_dic = new Dictionary<string, string>();
                        foreach (Match t_mc in t_ma)
                        {
                            if (t_mc.Groups.Count > c_book_link_index)
                            {
                                if (!t_dic.ContainsKey(t_mc.Groups[c_book_link_index].Value.ToString()))
                                {
                                    t_dic.Add(t_mc.Groups[c_book_link_index].Value.ToString(), t_mc.Groups[c_book_name_index].Value.ToString());
                                }

                            }
                        }
                    }
                }
                return t_dic;
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说列表地址失败" + ex.ToString());
            }

            return t_dic;
        }



        /// <summary>
        /// 收集某个地址的所有小说详情地址
        /// </summary>
        /// <param name="i_book_list_url"></param>
        /// <returns>小说地址及小说名称</returns>
        public Dictionary<string, string> CollectBookList(string i_book_list_url)
        {
            Dictionary<string, string> t_dic = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_list_url, m_site_encoding);
                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, c_reg_book, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma != null && t_ma.Count > 0)
                    {
                        t_dic = new Dictionary<string, string>();
                        foreach (Match t_mc in t_ma)
                        {
                            if (t_mc.Groups.Count > c_book_link_index)
                            {
                                if (!t_dic.ContainsKey(t_mc.Groups[c_book_link_index].Value.ToString()))
                                {
                                    t_dic.Add(t_mc.Groups[c_book_link_index].Value.ToString(), t_mc.Groups[c_book_name_index].Value.ToString());
                                }
                              
                            }
                        }
                    }
                }
                return t_dic;
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说列表地址失败" + ex.ToString());
            }

            return t_dic;
        }

        /// <summary>
        /// 收集某本小说详细信息
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public BookInfo CollectBookItem(string i_book_url)
        {
            BookInfo t_book = null;
          
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_url, m_site_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {

                    Match t_mc = Regex.Match(t_html, "<div[^<>]*id=[\'\"]*content[\'\"]*>.*?<h1>《(.*?)》</h1>.*?<a.*?>(.*?)</a>.*?<td.*?>.*?<a.*?>(.*?)</a>\\s*?\\|(.*?)\\s*?\\|", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count >= 3)
                    {
                        t_book = new BookInfo();
                        t_book.BookUrl = i_book_url;

                        t_book.BookName = t_mc.Groups[1].Value.ToString();
                        t_book.AuthorName = t_mc.Groups[2].Value.ToString();
                        t_book.BookSubCagegoryName = t_mc.Groups[3].Value.ToString();
                        t_book.BookStatus = t_mc.Groups[4].Value.ToString();
                        t_mc = Regex.Match(t_html, "点击：(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        long t_click = 0;
                        if (!long.TryParse(t_mc.Groups[1].Value.ToString(), out t_click))
                            t_click = 0;

                        t_book.Click = t_click;
                        t_mc = Regex.Match(t_html, "收藏：(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        long t_collect = 0;
                        if (!long.TryParse(t_mc.Groups[1].Value.ToString(), out t_collect))
                            t_collect = 0;

                        t_book.Collect = t_collect;

                       t_mc=Regex.Match(t_html,"<a[^<>]*?href=[\'\"]*?#[\'\"]*?>\\s*?<img[^<>]*srcs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>.*?<font[^<>]*class=[\'\"]*poptext[\'\"].*?>.*?</font>.*?<h2>.*?<font[^<>]*class=[\'\"]*poptext[\'\"].*?>.*?</font>(.*?)</td>",RegexOptions.IgnoreCase|RegexOptions.Compiled);

                        t_book.ImageUrl = t_mc.Groups[1].Value.ToString();

                        t_book.Description = t_mc.Groups[2].Value.ToString();

                        if (!string.IsNullOrEmpty(t_book.ImageUrl) && t_book.ImageUrl.IndexOf("s.jpg")>-1)
                            t_book.IsExistsImage = true;

                        t_mc = Regex.Match(t_html, "<li>.*?<a[^<>]*hrefs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>点击阅读</a></li>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        if (t_mc != null)
                        {
                            t_book.ChapterUrl = string.Format("http://www.3zcn.com{0}", t_mc.Groups[1].Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说详情失败" + ex.ToString());
            }

            return t_book;
        }


        /// <summary>
        /// 收集某本书的所有章节
        /// </summary>
        /// <param name="i_chapter_list_url"></param>
        /// <returns></returns>
        public List<BookChapterInfo> CollectChapterList(string i_chapter_list_url)
        {
            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            string t_site_book_id = string.Empty;
            Match t_mc = Regex.Match(i_chapter_list_url, "\\/(.*?)\\.html", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            if (t_mc != null)
            {
                t_site_book_id = t_mc.Groups[1].Value.ToString();
              
            }
            string t_html = string.Empty;
            MatchCollection t_ma = null;
            string t_volume_name = string.Empty;
            string t_sub_html = string.Empty;
            try
            {
                t_html = NetSiteCatchManager.ReadUrl(i_chapter_list_url, m_site_encoding);
                t_ma = Regex.Matches(t_html, c_volume_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_ma != null && t_ma.Count > 1)
                {
                    for (int t_index = 0; t_index < t_ma.Count - 1; t_index++)
                    {
                        t_volume_name = t_ma[t_index].Groups[1].Value.ToString();

                        t_sub_html = t_html.Substring(t_ma[t_index].Groups[1].Index, t_ma[t_index + 1].Groups[1].Index - t_ma[t_index].Groups[1].Index);
                        t_chapter_list.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));

                    }

                    t_volume_name = t_ma[t_ma.Count - 1].Groups[1].Value.ToString();
                    t_sub_html = t_html.Substring(t_ma[t_ma.Count - 1].Index);

                    t_chapter_list.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));

                }
                else
                {
                    t_chapter_list.AddRange(ParseChapter("第一卷", t_html, t_site_book_id));
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节列表失败" + ex.ToString());
            }

           

            return t_chapter_list;
        }

        /// <summary>
        /// 解析章节信息
        /// </summary>
        /// <param name="i_volume_name"></param>
        /// <param name="i_text"></param>
        /// <param name="i_site_book_id"></param>
        /// <returns></returns>
        private List<BookChapterInfo> ParseChapter(string i_volume_name, string i_text, string i_site_book_id)
        {
            if (string.IsNullOrEmpty(i_text))
                return new List<BookChapterInfo>();

            if (string.IsNullOrEmpty(i_volume_name))
            {
                i_volume_name = "残卷";
            }
            if (i_volume_name.IndexOf("收藏到书架") > -1)
            {
                i_volume_name = "第一卷";
            }

            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            MatchCollection t_ma = Regex.Matches(i_text, c_chapter_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);

            string t_chapter_name = string.Empty;
           
            if (t_ma != null)
            {

                foreach (Match t_mc in t_ma)
                {
                    if (t_mc.Groups.Count >= 2)
                    {
                        BookChapterInfo t_chapter = new BookChapterInfo();
                        t_chapter.VolumeName = i_volume_name;
                        t_chapter.UpdateTime = DateTime.Now;
                        t_chapter.WordsCount = 0;        
                        t_chapter.ChapterName = t_mc.Groups[2].Value.ToString();
                        t_chapter.Comfrom = string.Format("http://www.3zcn.com{0}", t_mc.Groups[1].Value.ToString());
                        t_chapter.IsVip = false;
                        t_chapter_list.Add(t_chapter);
                    }
                }
            }
           
            //排序
            if (t_chapter_list != null && t_chapter_list.Count > 0)
            {
                //多少行
                int t_total_row_count = t_chapter_list.Count % 8 == 0 ? t_chapter_list.Count / 8: t_chapter_list.Count / 8+1;

                //只有一行
                if (t_total_row_count == 1)
                {
                    return GetSortChapter(t_chapter_list);
                }

                List<BookChapterInfo> t_sort_chapter_list = new List<BookChapterInfo>();

                for (int index = 0; index < t_total_row_count-1; index++)
                {
     
                    if (index * 8 + 0 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 0]);
                    }

                    if (index * 8 + 2 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 2]);
                    }

                    if (index * 8 + 4 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 4]);
                    }

                    if (index * 8 + 6 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 6]);
                    }

                    if (index * 8 + 1 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 1]);
                    }

                    if (index * 8 + 3 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 3]);
                    }

                    if (index * 8 + 5 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 5]);
                    }

                    if (index * 8 + 7 < t_chapter_list.Count)
                    {
                        t_sort_chapter_list.Add(t_chapter_list[index * 8 + 7]);
                    }
                }

                t_sort_chapter_list.AddRange(GetSortChapter(t_chapter_list.GetRange((t_total_row_count-1) * 8, t_chapter_list.Count - (t_total_row_count-1) * 8)));

                return t_sort_chapter_list;

                
            }
            return null;
          
        }

        private List<BookChapterInfo> GetSortChapter(List< BookChapterInfo> i_chapter_list)
        {
            List<BookChapterInfo> t_sort_chapter_list = new List<BookChapterInfo>();
            if (i_chapter_list.Count < 5)
                return i_chapter_list;

            if (i_chapter_list.Count == 5)
            {
                t_sort_chapter_list.Add(i_chapter_list[0]);
                t_sort_chapter_list.Add(i_chapter_list[2]);
                t_sort_chapter_list.Add(i_chapter_list[3]);
                t_sort_chapter_list.Add(i_chapter_list[4]);
                t_sort_chapter_list.Add(i_chapter_list[1]);

            }
            if (i_chapter_list.Count == 6)
            {
                t_sort_chapter_list.Add(i_chapter_list[0]);
                t_sort_chapter_list.Add(i_chapter_list[2]);
                t_sort_chapter_list.Add(i_chapter_list[4]);
                t_sort_chapter_list.Add(i_chapter_list[5]);
                t_sort_chapter_list.Add(i_chapter_list[1]);
                t_sort_chapter_list.Add(i_chapter_list[3]);
            }
            if (i_chapter_list.Count == 7)
            {
                t_sort_chapter_list.Add(i_chapter_list[0]);
                t_sort_chapter_list.Add(i_chapter_list[2]);
                t_sort_chapter_list.Add(i_chapter_list[4]);
                t_sort_chapter_list.Add(i_chapter_list[6]);
                t_sort_chapter_list.Add(i_chapter_list[1]);
                t_sort_chapter_list.Add(i_chapter_list[3]);
                t_sort_chapter_list.Add(i_chapter_list[5]);
            }
            if (i_chapter_list.Count == 8)
            {
                t_sort_chapter_list.Add(i_chapter_list[0]);
                t_sort_chapter_list.Add(i_chapter_list[2]);
                t_sort_chapter_list.Add(i_chapter_list[4]);
                t_sort_chapter_list.Add(i_chapter_list[6]);
                t_sort_chapter_list.Add(i_chapter_list[1]);
                t_sort_chapter_list.Add(i_chapter_list[3]);
                t_sort_chapter_list.Add(i_chapter_list[5]);
                t_sort_chapter_list.Add(i_chapter_list[7]);
            }
            return t_sort_chapter_list;
        }

        /// <summary>
        /// 收集章节内容
        /// </summary>
        /// <param name="i_chapter_content_url"></param>
        /// <returns></returns>
        public string CollectChapterContent(string i_chapter_content_url)
        {
            string t_chapter_content = string.Empty;
            string t_chapter_content_reg = "<tr>.*?<td[^<>]*id=[\'\"]*content3zcn[^<>]*>(.*?)<font[^<>]*class=[\'\"]*tips[\'\"]*>";
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, m_site_encoding);
                if (!string.IsNullOrEmpty(t_html))
                {
                    Match t_mc = Regex.Match(t_html, t_chapter_content_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 0)
                    {
                        t_chapter_content = t_mc.Groups[1].Value.ToString();
                        //100字以上才算章节
                        if (!string.IsNullOrEmpty(t_chapter_content) && t_chapter_content.Length > 100)
                        {
                            t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);
                            t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);

                        }

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节内容失败" + ex.ToString());
            }

            return t_chapter_content;
        }

      
        /// <summary>
        /// 添加章节内容
        /// </summary>
        /// <param name="i_file_name"></param>
        /// <param name="i_book_chapter_content"></param>
        /// <returns></returns>
        public int InsertBookChapterContent(string i_book_category_id, long i_book_id, long i_chapter_id, string i_book_chapter_content)
        {
            FileManager t_file_mgr = new FileManager();
            try
            {
                return t_file_mgr.WriteBookContent(i_book_category_id,i_book_id, i_chapter_id, i_book_chapter_content);
            }
            catch (Exception ex)
            {
                LogHelper.Error("添加章节内容失败" + ex.ToString());
                return Consts.Faild;
            }
        }

        /// <summary>
        /// 下载小说封面
        /// </summary>
        /// <param name="i_book_icon_url"></param>
        /// <param name="i_save_file_name"></param>
        /// <returns></returns>
        public int DownLoadBookICON(string i_book_icon_url, long i_book_id)
        {
            try
            {
                return NetSiteCatchManager.DownLoadImage(i_book_icon_url, i_book_id);
            }
            catch (Exception ex)
            {
                LogHelper.Error("下载小说封面失败" + ex.ToString());
                return Consts.Faild;
            }

        }


     
    }
}
